package codingPractice.xiaolincoding;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

//使用BlockingQueue实现生产消费模式；它具有线程安全性
/*
 * 当队列为空时，从队列中获取元素的操作将会被阻塞，直到有元素被添加到队列中；
 * 当队列已满时，向队列中添加元素的操作将会被阻塞，直到有空间可用；
 * 支持多线程并发操作，保证线程安全。
 * 提供了一些阻塞的方法，如put和take，可以实现线程的等待和唤醒机制。
 */
public class ProducerConsumerModel {
    public static void main(String[] args) {
        //共享的缓冲区大小为2
        BlockingQueue<Integer> buffer = new LinkedBlockingDeque<>(3);
        Thread producerThread = new Thread(new Producer(buffer));
        Thread consumerThread = new Thread(new Consumer(buffer));
        producerThread.start();
        consumerThread.start();
    }

    public static class Producer implements Runnable {
        private BlockingQueue<Integer> buffer;
        public Producer(BlockingQueue<Integer> buffer) {
            this.buffer = buffer;
        }
        public void run() {
            for(int i=0; i<10; i++) {
                try {
                    buffer.put(i);
                    System.out.println("Produced: " + i);
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static class Consumer implements Runnable {
        private BlockingQueue<Integer> buffer;
        public Consumer(BlockingQueue<Integer> buffer) {
            this.buffer = buffer;
        }
        public void run () {
            while (true) {
                try {
                    int value = buffer.take();
                    System.out.println("Consumed: " + value);
                    Thread.sleep(30);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        
    }
}
